﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Reflection;

namespace WPF.Controls.QuerySelector
{
    public class OneEventTriggerBehavior<T1, T2>
    {
        private UIElement _element;
        private EventInfo _info;
        private Delegate _handler;
        private Delegate _currentHandler;
        private RoutedEvent _routedEvent;
        public OneEventTriggerBehavior(UIElement element, string eventName, Delegate handler)
        {
            _element = element;
            _handler = handler;
            _info = _element.GetType().GetEvent(eventName);
            _currentHandler = Delegate.CreateDelegate(_info.EventHandlerType, this, "Invoke");
            _info.AddEventHandler(_element, _currentHandler);
        }

        public OneEventTriggerBehavior(UIElement element, RoutedEvent routedEvent, Delegate handler)
        {
            _routedEvent = routedEvent;
            _element = element;
            _handler = handler;
            _currentHandler = Delegate.CreateDelegate(routedEvent.HandlerType, this, "Invoke");
            element.AddHandler(routedEvent, _currentHandler);
        }

        private void Invoke(T1 sender, T2 e)
        {
            var parameters = _handler.Method.GetParameters();
            _handler.DynamicInvoke(parameters);
            if (_routedEvent != null)
            {
                _element.RemoveHandler(_routedEvent, _currentHandler);
                _routedEvent = null;
            }
            else
                _info.RemoveEventHandler(_element, _currentHandler);
        }
    }
}
